﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.ComponentModel;

namespace Shop.Infrastructure.Extensions
{
    public static class ObjectExtensions
    {
        /// <summary>
        /// 深度拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static T DeepClone<T>(this T source)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, source);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }

        /// <summary>
        /// 匿名类型转成字典类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Dictionary<string, object> AnonymousObjectToDict(this object obj)
        {
            Dictionary<string, object> dict = null;
            if (obj != null)
            {
                dict = new Dictionary<string, object>();
                foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj))
                {
                    dict.Add(property.Name.Replace('_', '-'), property.GetValue(obj));
                }
            }
            return dict;
        }
    }
}
